package com.thinqq.tracktask.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Transaction;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.thinqq.tracktask.client.TaskService;
import com.thinqq.tracktask.server.Store.Api;
import com.thinqq.tracktask.server.Store.Task;
import com.thinqq.tracktask.server.Store.User;
import com.thinqq.tracktask.shared.FieldVerifier;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class TaskServiceImpl extends RemoteServiceServlet implements TaskService {
	
	private final Store store = new Store("transactions-optional");
	
	public void addTask(String input) throws IllegalArgumentException {
		if (!FieldVerifier.isValidName(input)) {
			throw new IllegalArgumentException("Task not valids");
		}

//		String serverInfo = getServletContext().getServerInfo();
//		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		
		Api api = store.getApi();
		//TODO:We need to handle user session management 
		//Get details from session and get the user
		User user = api.getUser("1001");
		input = escapeHtml(input);
		api.addTask(user, input);
		api.saveUser(user);
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

	@Override
	public List<String> getTaskList() {
		List<String> taskNameList = new ArrayList<String>();
		Api api = store.getApi();
		User user = api.getUser("1001");
		List<Task> taskList = api.getAllTask(user);
		for (Task task : taskList) {
			taskNameList.add(task.getTaskName());
		}
		
		return taskNameList;
	}
}
